package com.imooc.project.controller;
/**
 * Description:
 * <p>
 * ClassName: LoginController
 * date: 2021/8/20 9:37
 *
 * @author Yin.Liu
 * @version 1.0
 * @since JDK 1.8
 */

import com.imooc.project.dto.LoginDTO;
import com.imooc.project.service.IAccountService;
import com.imooc.project.service.IResourceService;
import com.imooc.project.vo.ResourceVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @ClassName LoginController
 * @Description 登录的构造器
 * @Author Yin.Liu8
 * @Date 2021/8/20 9:37
 * @Version 1.0
 */
@Controller
@RequestMapping("auth")
public class LoginController {
    @Autowired
    private IAccountService accountService;

    @Autowired
    private IResourceService resourceService;

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("login")
    public String login(String username, String password, HttpSession session,
                        RedirectAttributes redirectAttributes, Model model) {
        LoginDTO login = accountService.login(username, password);
        //取错误信息
        String error = login.getError();
        if (error == null) {
            session.setAttribute("account", login.getAccount());
            List<ResourceVO> resourceVOS = resourceService
                    .listResourceByRoleId(login.getAccount().getRoleId());
            model.addAttribute("resources", resourceVOS);
        } else {
            redirectAttributes.addFlashAttribute("error", error);
        }

        return login.getPath();

    }

    @GetMapping("logout")
    public String logout(HttpSession httpSession) {
        //销毁session
        httpSession.invalidate();
        return "redirect:/";
    }
}
